home *** CD-ROM | disk | FTP | other *** search
- Path: rain.fr!world-net!usenet
- From: Frederic LACHASSE <lachass@worldnet.fr>
- Newsgroups: comp.lang.c++
- Subject: Re: Can copy constructor and operator= share code?
- Date: Fri, 08 Mar 1996 21:39:48 +0000
- Organization: World-Net information exchange, Internet provider.
- Message-ID: <VA.0000005e.00026e75@fred>
- References: <4hinsg$ooq@dekalb.dc.peachnet.edu>
- Reply-To: lachass@worldnet.fr
- NNTP-Posting-Host: client145.sct.fr
- X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
-
- In article <4hinsg$ooq@dekalb.dc.peachnet.edu>,
- williamh@dekalb.dc.peachnet.edu (darlene williams) wrote:
- >
- > i have adopted using a "copy()" member function; the benefit is a single
- > piece of code, and the cost is the probable double-initialization of
- > class members:
- >
- > class foo
- > {
- > public:
- > foo () { }
- > foo &operator = (const foo &rhs) { copy (rhs); return (*this); }
- > foo (const foo &rhs) { copy (rhs); }
- > void copy (const foo &rhs) { b = rhs.b; }
- > private:
- > bar b;
- > };
- >
- > >T &T::operator =(const T &t) { ~T(); new(this) T(t); }
- >
- > this is a somewhat interesting approach, but destruction isn't
- > always the same as "resetting" the object to a pre-copy state.
- > i prefer including a "reset()" function whose semantics imply
- > 'reset to at-construction state', and not have to worry about
- > any side-effects of destroying the object:
- > T &T::operator = (const T &t) { reset(); copy(t); return(*this); }
-
- So what do you do in your destructor? call reset()? If you're doing something
- else, I think there is a problem in your class design.
-
- I do not see much differences between writing:
-
- class foo
- {
- void copy(const foo &f);
- void reset();
- public:
- foo(const foo &f) { copy(f); }
- ~foo() { reset(); }
- foo &operator =(const foo &f) { reset(); copy(f); return *this; }
- };
-
- and:
-
- class foo
- {
- public:
- foo(const foo &);
- ~foo();
- foo &operator =(const foo &f) { ~foo(); new(this) foo(f); return *this; }
- };
-
- except the important feature allowed by the 2nd formulation: the use of an
- initializer list in the copy constructor.
-
- Frederic LACHASSE (ECP 86)
- CompuServe: 100530,2005
- Internet: lachass@worldnet.fr
-
-